package controllers

import (
	"fmt"
	"path/filepath"

	"cvevulner/common"
	"cvevulner/models"
	"cvevulner/util"

	"github.com/astaxie/beego"
)

// FileController file operation routing processing
type FileController struct {
	beego.Controller
}

// DownloadLastExcel Download the latest excel file
// @router /lastExcel [get]
func (f *FileController) DownloadLastExcel() {
	fd := beego.AppConfig.DefaultString("fileDir", "download")
	err := common.CreateDir(fd)
	er := models.ExportRecord{}
	err = er.QueryLast()
	if err != nil {
		_ = f.Ctx.Output.Body([]byte("no file "))
	}
	fp := filepath.Join(fd, er.FileName)
	if ex, _ := util.IsExistPath(fp); !ex {
		_ = f.Ctx.Output.Body([]byte("no file "))
	}
	f.Ctx.Output.Download(fp, er.FileName)
}

// DownLoadExcelByFileCode download excel file by code
// @router /downloadExcel
func (f *FileController) DownLoadExcelByFileCode() {
	fd := beego.AppConfig.DefaultString("fileDir", "download")
	common.CreateDir(fd)
	fc := f.GetString("fileCode")
	if fc == "" {
		_ = f.Ctx.Output.Body([]byte("err: fileCode is a required parameter "))
		return
	}
	er := models.ExportRecord{FileCode: fc}
	err := er.Read("file_code")
	if err != nil {
		_ = f.Ctx.Output.Body([]byte(fmt.Sprintf("err: %v", err)))
		return
	}
	if er.FileName == "" {
		_ = f.Ctx.Output.Body([]byte("err: Can not find excel file by fileCode! "))
		return
	}
	if er.State == 0 {
		_ = f.Ctx.Output.Body([]byte("The file is being generated, please try again later!"))
		return
	}
	if er.State == 2 {
		_ = f.Ctx.Output.Body([]byte("File generation failed, please contact the administrator or regenerate!!"))
		return
	}
	fp := filepath.Join(fd, er.FileName)
	if ex, _ := util.IsExistPath(fp); !ex {
		_ = f.Ctx.Output.Body([]byte("error:file does not exist"))
	}
	f.Ctx.Output.Download(fp, er.FileName)
}
